import 'package:flutter/cupertino.dart';
import 'package:flutterproject/mvvm/base/base_controller.dart';
import 'package:flutterproject/page/setting/children/address/data/address_bean.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:get/get.dart';

class AddAddressController extends BaseController {
  TextEditingController nameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController areaController = TextEditingController();
  TextEditingController streetController = TextEditingController();
  HttpClient client = Get.find<HttpClient>();
  AddressBean? bean = Get.arguments ?? AddressBean();

  @override
  void onInit() {
    super.onInit();
    nameController.text = bean?.name ?? "";
    phoneController.text = bean?.tel ?? "";
    areaController.text = bean?.base ?? "";
    streetController.text = bean?.detail ?? "";
  }

  void changeTop() {
    if (bean?.top == null || bean?.top == 0) {
      bean?.top = 1;
    } else {
      bean?.top = 0;
    }
    update();
  }

  Future updateAddress() async {
    if(phoneController.text.length < 11){
      ToastUtil.showTips("请输入11位手机号");
      return;
    }
    try {
      DialogUtil.showLoading();
      bean?.base = areaController.text;
      bean?.detail = streetController.text;
      bean?.tel = phoneController.text;
      bean?.name = nameController.text;
      bean?.top ??= 0;
      await client.post(AddressManager.addressUpdate, data: bean?.toJson());
      ToastUtil.showFailed("编辑成功!");
      Get.back();
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  Future deleteAddress() async {
    try {
      DialogUtil.showLoading();
      await client.post(AddressManager.addressDelete, data: bean?.toJson());
      ToastUtil.showFailed("删除成功!");
      Get.back();
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }
}
